package com.animation_study.eventbus

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.TextView
import com.animation_study.R
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class EventBusActivity : AppCompatActivity() {

    //?代表变量可以为空
    var tv_get_msg: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_bus)

        tv_get_msg = this.findViewById(R.id.tv_get_msg) as TextView?
        EventBus.getDefault().register(this);
    }

    fun send(view: View) {
        EventBus.getDefault().post(MessageEvent("name", "password"))
    }

    fun sendsticky(view: View) {
        EventBus.getDefault().postSticky(StickyEvent("我发送一个黏性事件"))
    }

    fun receive(view: View) {
        startActivity(Intent(this, ReceiveMsgActivity::class.java))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun messageEventBus(event: MessageEvent) {
        tv_get_msg!!.setText(event.password)
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun messageEventBussticky(event: StickyEvent) {
        tv_get_msg!!.setText(event.msg)
    }

    override fun onDestroy() {
        EventBus.getDefault().removeAllStickyEvents()
        super.onDestroy()
    }

}
